package com.nwcl.common.interceptors;


import com.alibaba.fastjson.JSON;
import com.nwcl.common.conf.WxYsxBeanConf;
import com.nwcl.common.result.ErrorCode;
import com.nwcl.common.result.Result;
import com.nwcl.common.utils.SessionUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private WxYsxBeanConf wxYsxBeanConf;
    @Autowired
    private SessionUtil sessionUtil;
    private Logger log = LogManager.getLogger(LoginInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html;charset=UTF-8");
        response.addHeader("Cache-Control", "no-cache");//浏览器和缓存服务器都不应该缓存页面信息
        response.addHeader("Cache-Control", "no-store");//请求和响应的信息都不应该被存储在对方的磁盘系统中；
        response.addHeader("Cache-Control", "must-revalidate");//于客户机的每次请求，代理服务器必须想服务器验证缓存是否过时；
        //不允许浏览器端或缓存服务器缓存当前页面信息。
        String url = request.getServletPath();
        String servername = request.getServerName();
        log.info("拦截请求：url:{},servername:{}", url, servername);
        if (servername.equals(wxYsxBeanConf.getYsxServername())) {
            return handleYsx(request, response);
        }
        log.warn("登录拦截请求4001{}", url);
        Result r = Result.fail(ErrorCode._403[0], ErrorCode._403[2]);
        response.getWriter().write(JSON.toJSONString(r));
        return false;
    }

    private boolean handleYsx(HttpServletRequest request,
                              HttpServletResponse response) throws IOException {
        boolean b = sessionUtil.updateSession(request);
        //校验顺序：1：校验是否登录
        if (!b) {//如果是异步请求，并且session为空
            String wxUrl = "";
            Result r = Result.fail(wxUrl, ErrorCode._4001[0]);
            response.getWriter().write(JSON.toJSONString(r));
            return false;
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }


}
